const puppeteer = require('puppeteer');
const base = `https://movie.douban.com/subject/`;

const sleep = time => new Promise(resolve => {
  setTimeout(resolve,time)
});

process.on('message',async movies=>{

  console.log('Start visit the target page')

  const browser = await puppeteer.launch({
    args:['--no-sandbox'],
    dumpio:false
  })

  const page = await browser.newPage()

  for(let i=0;i<movies.length;i++){
    let doubanId = movies[i].doubanId
    await page.goto(base + doubanId,{
      waitUntil:'networkidle2'
    })

    await sleep(1000)

    const result = await page.evaluate(()=>{
      var $ = window.$
      var item = $('.related-pic-video')

      if(item && item.length>0){
        var link = item.attr('href')
        var cover = item.find('img').attr('src')

        return{
          link,
          cover
        }
      }
      return {}
    })

    let video

      if(result.link){
        await page.goto(result.link,{
          waitUntil:'networkidle2'
        })

        await sleep(2000)

        video = await page.evaluate(() =>{
          var $ = window.$
          var item = $('source')

          if(item && item.length>0){
            return item.attr('src')
          }
          return ''
        })

      }

      const data = {
        video,
        doubanId,
        cover:result.cover
      }
    process.send(data)
  }
  browser.close()
  process.exit(0)

})
